﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using App_Code;
using TwitterStatisticsModel;
using System.Linq;

public partial class Stats_Keywords : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    private void KeywordAdd(string keyword)
    {
        var entities = Context.GetEntityContext();
        SearchKeyword key = new SearchKeyword {Keyword = keyword};
        var duplicate = (from k in entities.Keywords where k.Keyword == key.Keyword select k).FirstOrDefault();
        if (duplicate == null)
        {
            entities.Keywords.AddObject(key);
            entities.SaveChanges();
            try
            {
                Collector.CollectTweets(key.Keyword);
            }
            catch(ArgumentException ex)
            {
                Response.Write(ex.Message);
            }
            //todo переделать говнецо с эксепшенами
        }
    }
    protected void AddKeyword_Click(object sender, EventArgs e)
    {
        KeywordAdd(KeywordName.Text);
        KeywordName.Text = String.Empty;
        AllKeywords.DataBind();
    }
    protected void AllKeywords_SelectedIndexChanged(object sender, EventArgs e)
    {
        var row = AllKeywords.SelectedRow;
        string keyword = row.Cells[1].Text;
        Response.Redirect("Statistics.aspx?keyword="+keyword);
    }
    protected void AllKeywords_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        var entities = Context.GetEntityContext();
        string key = (string) e.Values[0];
        SearchKeyword keyword = (from k in entities.Keywords where k.Keyword == key select k).FirstOrDefault();
        Collector.StopCollecting(keyword.Keyword);
        foreach (var tweetStored in entities.Tweets)
        {
            if (tweetStored.Keywords.Contains(keyword) && tweetStored.Keywords.Count == 1)
            {
                entities.Tweets.DeleteObject(tweetStored);
            }
        }
        entities.SaveChanges();
    }
}